package snu.abba;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;

public class ABBA extends ListActivity {
    /** Called when the activity is first created. */
	
	private static final String MEDIA_PATH = new String("/sdcard/");
	private List<String> songs = new ArrayList<String>();
	private List<String> songsPath = new ArrayList<String>();
	ArrayAdapter<String> songList;
	private MediaPlayer mp = new MediaPlayer();
	private int currentPosition = 0;
	boolean isPaused = false;
	Animation anim = null;
	SeekBar bar;
	boolean isRandomPlay = false;

	@Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		anim = AnimationUtils.loadAnimation( this, R.anim.magnify );
        setContentView(R.layout.main);
        bar = (SeekBar) findViewById(R.id.progress_horizontal);
        bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromTouch) {
				// TODO Auto-generated method stub
				if(fromTouch && mp.isPlaying()) {
					seek(progress);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
        	
        });
        bar.setProgress(0);
        initUI();
        updateSongList();
        
	}
	
    protected void seek(int progress) {
    	float prg_float = progress;
		float totmsec = (float)mp.getDuration();
		int msec = (int) (totmsec*(prg_float/1000));
    	mp.seekTo(msec);
	}

	public void initUI(){   
    ImageButton play = (ImageButton) findViewById(R.id.play);
    play.setOnClickListener(new ImageButton.OnClickListener() {
    	public void onClick(View v) {
    		
    		if(isPaused){
    			mp.start();
    			setTitle("Playing: " + songs.get(currentPosition));
    			isPaused = false;
    			return;
    		}
    		if(mp.isPlaying()){
    			return;
    		}
    		
    		try {
    			if(isRandomPlay)
    				RandomPos();
    			
				playMedia(songsPath.get(currentPosition));
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
    	}
    });
    
    ImageButton stop = (ImageButton) findViewById(R.id.stop);
  
    stop.setOnClickListener(new ImageButton.OnClickListener() {
    	public void onClick(View v) {
    		
    		setTitle("Stopped: " + songs.get(currentPosition));
    		mp.seekTo(0);
    		mp.stop();
    		isPaused=false;
    		bar.setProgress(0);
    	}
    });
    
    ImageButton pause = (ImageButton) findViewById(R.id.pause);
    pause.setOnClickListener(new ImageButton.OnClickListener() {
    	public void onClick(View v) {
    		if(mp.isPlaying()){
    			setTitle("Paused: " + songs.get(currentPosition));
    			mp.pause();
    			isPaused = true;
    		}
    	}
    });
    
	 ImageButton next = (ImageButton) findViewById(R.id.next);
	    next.setOnClickListener(new ImageButton.OnClickListener() {
	    	public void onClick(View v) {
	    		if(!mp.isPlaying() && !isPaused){
	    			nextSong();
	    			isPaused=false;
	    			setTitle("Stoppped: " + songs.get(currentPosition));
	    			return;
	    		}
	    		else if(isPaused){
	    				isPaused=false;
	    				mp.stop();
	    		}
				nextSong();
			    // Play next song
				if(isRandomPlay)
    				RandomPos();
				playMedia(songsPath.get(currentPosition));
	    	}
	    });
	    
	
	 ImageButton prev = (ImageButton) findViewById(R.id.prev);
	    prev.setOnClickListener(new ImageButton.OnClickListener() {
	    	public void onClick(View v) {
	    		if(!mp.isPlaying() && !isPaused){
	    			prevSong();
	    			isPaused=false;
	    			setTitle("Stoppped: " + songs.get(currentPosition));
	    			return;
	    		}
	    		else if(isPaused){
	    			mp.stop();
	    			isPaused=false;
	    		}
	    		prevSong();
			    // Play prev song
	    		if(isRandomPlay)
    				RandomPos();
			    playMedia(songsPath.get(currentPosition));	
	    		}
	    });
	    
	
    final ToggleButton shuffle = (ToggleButton) findViewById(R.id.shuffle);
    shuffle.setTextOff("Shuffle");
    shuffle.setTextOn("Shuffle");
    shuffle.setChecked(false);
    shuffle.setOnClickListener(new Button.OnClickListener() {
    	public void onClick(View v) {
    		//System.exit(RESULT_OK);
    		if(isRandomPlay){
    			
    			isRandomPlay=false;
    			
    			shuffle.setChecked(false);
    		}
    		else{
    			shuffle.setChecked(true);
    			
    			isRandomPlay=true;
    		}
    	}
    });
    
    Button exit = (Button) findViewById(R.id.exit);
    
    exit.setOnClickListener(new ImageButton.OnClickListener() {
    	public void onClick(View v) {
    		
    		System.exit(RESULT_OK);
    	}
    });
	}
	public void playMedia (String songPath) {
		if(songPath==null){
			return;
		}
		mp.reset();
		try {
			mp.setDataSource(MEDIA_PATH + songPath);
			mp.prepare();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mp.start();
		isPaused=false;
		setTitle("Playing: " + songs.get(currentPosition));
		
		//TextView duration = (TextView) findViewById(R.id.playedtime);
		//duration.setText("Duration: "+formatTime());
		//bar.setProgress((bar.getProgress()+100));
		Thread pollThread = new Thread() {
		      public void run(){
		    	  while(true){
		        runOnUiThread(new Runnable() {
		        	public void run() {
		        		updatePlayedTime();
		        	}
		        });
		        try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		      }
		      }
		    };
		    pollThread.start();
		  
		
        mp.setOnCompletionListener(new OnCompletionListener(){

            // @Override
            public void onCompletion(MediaPlayer arg0) {
					nextSong();
					if(isRandomPlay)
	    				RandomPos();
					playMedia(songsPath.get(currentPosition));
            }
       }); 
	}
	 
    private void nextSong(){ 
          if (++currentPosition >= songs.size()) {
              // Last song, just reset
              currentPosition = 0;
          }
      }
	
    private void prevSong(){	  
        if (--currentPosition < 0) {
            // First song, just start from the end
            currentPosition = songs.size();
        }
    }
    
    public void updateSongList() {
  
          File folder = new File(MEDIA_PATH);
         
          
          if (folder.listFiles().length > 0) {
        	 
              for (File file : folder.listFiles()) { 
            	  if(file.getName().endsWith(".mp3")){
                	  try {  
                		  String artist = new String();
                          String song = new String();
                		  MP3File mp3 = new MP3File(file);
	      					if (mp3.hasID3v1Tag()) {
	      						ID3v1 tag = mp3.getID3v1Tag();
	      						artist = tag.getArtist();
	      						song = tag.getSongTitle();
	      				
	      					} 
	      					if (artist.length() > 0 && song.length() > 0){
	      						songs.add(artist + " - " + song);
	      					}
	      					else{
	      						songs.add(file.getName());
	      					}
	      					songsPath.add(file.getName());
	      					
                	  }	catch (IOException e) {
      					// TODO Auto-generated catch block
      					e.printStackTrace();
                	  } catch (TagException e) {
      					// TODO Auto-generated catch block
      					e.printStackTrace();
      				}  
            	  
            	  }
              }
              songList = new ArrayAdapter<String>(this,R.layout.song_item, songs);
              setListAdapter(songList);
             
          }
      }
 
    public void RandomPos (){
    	int length = songs.size()-1;
    	currentPosition = (int)Math.round((float)length*Math.random());
    }
   
    protected void onListItemClick(ListView l, View v, int position, long id) {

        currentPosition = position;
  	  	//v.startAnimation( anim );
        try {
			playMedia(songsPath.get(position));
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    } 
    

    private void updatePlayedTime() {
    	int played = 0;
    	int total = 0;
    	int playedsec = 0;
    	int totalsec = 0;
    	int playedmin = 0;
    	int totalmin = 0;
    	
    	played = mp.getCurrentPosition(); //the current position in ms
    	total = mp.getDuration(); //total length in ms
    	playedsec = played/1000; //time in seconds
    	totalsec = total/1000;
    	
    	playedmin = playedsec/60; //minutes played
    	playedsec = playedsec - (playedmin*60); //seconds played
    	
    	totalmin = totalsec/60; //minutes total
    	totalsec = totalsec - (totalmin*60);//seconds total (sort of)
    	
    	float progresspromille = ((float)played/(float)total)*1000;
    	
    	int progress = (int)progresspromille;
    	//ProgressBar bar = (ProgressBar) findViewById(R.id.progress_horizontal);
    	bar.setProgress(progress);
    	
    	
    	TextView playedtime = (TextView) findViewById(R.id.playedtime);
    	String text = null;
    	text = String.format("%02d:%02d / %02d:%02d", playedmin, playedsec, totalmin, totalsec);
    	playedtime.setText(text);
    }
    
    
}



